package net.nampham.visioncontrol;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import net.nampham.visioncontrol.model.Angle;
import net.nampham.visioncontrol.model.CONFIG;
import net.nampham.visioncontrol.model.DColor;
import net.nampham.visioncontrol.model.TriangleMesh;
import net.nampham.visioncontrol.model.Vec2;
import net.nampham.visioncontrol.view.RColor;
import net.nampham.visioncontrol.view.Vec3;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.SystemClock;
import android.view.MotionEvent;

public class MainRenderer2 extends GLSurfaceView implements GLSurfaceView.Renderer{

	Context mContext;
	net.nampham.visioncontrol.view.Renderer mRenderer;
	TriangleMesh mMesh;
	
	public MainRenderer2(Context context) {
		super(context);
		mContext = context;
		mMesh = new TriangleMesh();
	}
	
	private float cur_angle = 45;
	private void draw_scene(float elapsed){
		mMesh.DebugDraw();
		mMesh.FindVision(new Vec2(0.5f,0.3f), Angle.FromDegree(cur_angle));
		
		cur_angle += elapsed*40;
		/*
		mRenderer.render_line(new Vec3(0,0,0), new Vec3(5,5,0), new RColor(1, 0, 0));
		mRenderer.render_line(new Vec3(5,0,0), new Vec3(0,5,0), new RColor(1, 0, 0));
		*/
	}
	
	Vec2 basePointer;
	Vec3 baseEye;
	@Override
	public boolean onTouchEvent(MotionEvent event){
		//TODO: finish this
		int pcount = event.getPointerCount();
		//if (pcount>1) return false;
		int action = event.getAction();
		switch (action){
		case MotionEvent.ACTION_DOWN:
		//case MotionEvent.ACTION_POINTER_DOWN:
		//	if (pcount==2){
				basePointer = new Vec2(event.getX(), event.getY());
				baseEye = mRenderer.mEyePos;				
		//	}
			break;
		case MotionEvent.ACTION_MOVE:
		//	if (pcount==2){
				if (baseEye!=null){
					Vec2 offset = new Vec2(event.getX(), event.getY()).dec(basePointer);
					mRenderer.mEyePos = baseEye.add(new Vec3(offset).mul(0.02f));				
				}
		//	}
			break;
		case MotionEvent.ACTION_UP:
		//case MotionEvent.ACTION_POINTER_UP:
		//	if (pcount<2){
				baseEye = null;
		//	}
			break;
		}
		return true;
	}
	
	private float last_time;

	public void onDrawFrame(GL10 glUnused) {
		try{
			float cur_time = SystemClock.uptimeMillis();
			float elapsed_time = (cur_time-last_time)/1000.0f;
			draw_scene(elapsed_time);
			mRenderer.render(elapsed_time);			
			last_time = cur_time;
		}catch (Exception ex){
			Logger.e(ex);
		}
	}

	public void onSurfaceChanged(GL10 glUnsued, int width, int height) {
		try{			
			mRenderer.resrouce_reset(width, height);
		}catch(Exception ex){
			Logger.e(ex);
		}
	}

	public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
		try{
			last_time = SystemClock.uptimeMillis();
			mRenderer = new net.nampham.visioncontrol.view.Renderer();
			CONFIG._DEBUGGER = mRenderer;
		}catch(Exception ex){
			Logger.e(ex);
		}		
	}
	

}
